package com.loyin.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import com.et.mvc.JsonView;
import com.et.mvc.TextView;
import com.et.mvc.View;
import com.igs.backup.DBBackupUtil;
import com.igs.parse.query.QueryCountUtil;
import com.loyin.model.MsgInfo;
import com.loyin.model.DownloadUrl;
import com.loyin.model.UserInfo;
import com.loyin.model.UserInfoVo;
import com.loyin.util.MD5;
import com.loyin.util.Page;

/***
 * 用户控制层
 * 
 * @author 刘声凤 2011-11-5
 */
public class UserInfoController extends ApplicationController
{
	private Logger log = Logger.getLogger(this.getClass());

	public void reg()
	{
	}

	public void home()
	{
	}
	
	
	/**
	 * 本方法为会员注册方法
	 * @param user
	 * @return
	 */
	public View save(UserInfo user)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		String checkcode = request.getParameter("checkcode");
		String ckcode = (String) session.getAttribute("check");
		if (checkcode == null || !checkcode.equals(ckcode))
		{
			map.put("stat", "F");
			map.put("msg", "验证码错误！");
			return new JsonView(map);
		}
		try
		{
			if (user.id == null || user.id == 0)
			{
				//or email =? or phone=?           { user.usercode, user.email, user.phone });
				List<UserInfo> ulist = (List<UserInfo>) user.findBySql(user.getClass(), "select * from igs_userinfo where usercode=? ", new Object[]
				{ user.usercode});
				if (ulist != null && ulist.isEmpty() == false)
				{
					map.put("stat", "F");
					map.put("msg", "已经存在此会员号、手机号、email！");
					return new JsonView(map);
				}
				//注册时间
				user.regtime = new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date());
				//到期时间，默认是3天
		        Date endDate=null;//取时间
		        Calendar calendar = new GregorianCalendar();
		        calendar.setTime(new Date());
		        calendar.add(calendar.DATE,3);//把日期往后增加3天.整数往后推,负数往前移动
		        endDate=calendar.getTime(); //这个时间就是日期往后推一天的结果       
		        user.setEffecttime(new java.text.SimpleDateFormat("yyyy-MM-dd").format(endDate));
				user.setLongtimeeffect(0);//默认注册的会员非长期有效
				user.setRoleclass(1);//0是管理员，1是普通用户
				user.setPwd(MD5.getMD5ofStr(user.getPwd()));
			}
			if (user.save() == true)
			{
				map.put("stat", "S");
				map.put("msg", "注册会员信息成功！");
				map.put("arg", user.id);
			} else
			{
				map.put("stat", "F");
				map.put("msg", "注册会员信息失败！");
			}
		} catch (Exception e)
		{
			log.error("注册异常", e);
			map.put("stat", "E");
			map.put("msg", "注册会员异常！");
		}
		return new JsonView(map);
	}

	public void upinfo()
	{
		UserInfoVo uservo = (UserInfoVo) session.getAttribute("user_session");
		UserInfo user = new UserInfo();
		try
		{
			user = user.find(user.getClass(), uservo.id);
			request.setAttribute("user", user);
		} catch (Exception e)
		{
			log.error("导航更新用户信息异常", e);
		}
	}
	
	/**
	 * 管理员修改用户信息
	 */
	public void updateuser(long id)
	{
		UserInfo user = new UserInfo();
		try
		{
			user = user.find(user.getClass(), id);
			request.setAttribute("user", user);
		} catch (Exception e)
		{
			log.error("导航更新用户信息异常", e);
		}
	}
	/**
	 * 管理员保存用户信息
	 */
	public View saveuser(UserInfoVo uservo)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		try
		{
			UserInfo user = new UserInfo();
			user = user.find(user.getClass(), uservo.id);
			user.protectQestion = uservo.protectQestion;
			user.protectAnswer = uservo.protectAnswer;
			user.firstname = uservo.firstname;
			user.lastname = uservo.lastname;
			user.sex = uservo.sex;
			user.phone = uservo.phone;
			user.email = uservo.email;
			if(uservo.effecttime!=null && uservo.effecttime.trim().equals("")==false)
			{
				user.effecttime=uservo.effecttime+" 00:00:00";
			}
			user.longtimeeffect=uservo.longtimeeffect;
			user.fullname=uservo.fullname;
			
			if (user.update() == true)
			{
				map.put("stat", "S");
				map.put("msg", "修改会员信息成功！");
				map.put("arg", uservo.id);
			} else
			{
				map.put("stat", "F");
				map.put("msg", "修改会员信息失败！");
			}
		} catch (Exception e)
		{
			log.error("修改异常", e);
			map.put("stat", "E");
			map.put("msg", "修改会员异常！");
		}
		return new JsonView(map);
	}

	public View update(UserInfoVo uservo)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		try
		{
			UserInfo user = new UserInfo();
			user = user.find(user.getClass(), uservo.id);
			user.protectQestion = uservo.protectQestion;
			user.protectAnswer = uservo.protectAnswer;
			user.firstname = uservo.firstname;
			user.lastname = uservo.lastname;
			user.sex = uservo.sex;
			user.phone = uservo.phone;
			user.email = uservo.email;
			user.fullname=uservo.fullname;
			if (user.update() == true)
			{
				map.put("stat", "S");
				map.put("msg", "修改会员信息成功！");
				map.put("arg", uservo.id);
			} else
			{
				map.put("stat", "F");
				map.put("msg", "修改会员信息失败！");
			}
		} catch (Exception e)
		{
			log.error("修改异常", e);
			map.put("stat", "E");
			map.put("msg", "修改会员异常！");
		}
		return new JsonView(map);
	}

	public void pwd()
	{
	}

	/**
	 * 修改密码
	 * 
	 * @param user
	 * @return
	 */
	public View updatepwd()
	{
		Map<String, Object> map = new HashMap<String, Object>();
		String oldpwd = request.getParameter("oldpwd");
		String newpwd = request.getParameter("newpwd");
		String pwd1 = request.getParameter("pwd1");
		UserInfoVo uservo = (UserInfoVo) session.getAttribute("user_session");
		try
		{
			if (uservo == null)
			{
				map.put("stat", "E");
				map.put("msg", "登录超时，请重新登录！");
				return new JsonView(map);
			}
			if (oldpwd == null || newpwd == null || pwd1 == null || "".equals(pwd1) || "".equals(oldpwd) || "".equals(oldpwd))
			{
				map.put("stat", "F");
				map.put("msg", "未输入密码，请重新输入！");
			} else
			{
				if (MD5.getMD5ofStr(oldpwd.trim()).equals(uservo.getPwd()) == false)
				{
					map.put("stat", "F");
					map.put("msg", "原密码错误，请重新输入！");
				} else
				{
					UserInfo user = new UserInfo();
					newpwd = MD5.getMD5ofStr(newpwd);
					int rs = user.execute("update igs_userinfo u set u.pwd=? where u.id=?", new Object[]
					{ newpwd, uservo.id });
					if (rs > 0)
					{
						map.put("stat", "S");
						map.put("msg", "修改密码成功！请牢记密码！");
						uservo.setPwd(newpwd);
					} else
					{
						map.put("stat", "F");
						map.put("msg", "修改密码失败！");
					}
				}
			}
		} catch (Exception e)
		{
			log.error("修改密码失败", e);
			map.put("stat", "E");
			map.put("msg", "修改密码失败！");
		}
		return new JsonView(map);
	}

	@SuppressWarnings("unchecked")
	public View login()
	{
		Map<String, Object> map = new HashMap<String, Object>();
		String usercode = request.getParameter("usercode");
		String pwd = request.getParameter("pwd");
		String checkcode = request.getParameter("checkcode");
		String ckcode = (String) session.getAttribute("check");
		UserInfo user = new UserInfo();
		try
		{
			if (checkcode != null && checkcode.toUpperCase().equals(ckcode.toUpperCase()))
			{

				List<UserInfo> userlist = (List<UserInfo>) user.findBySql(user.getClass(),
						"select * from igs_userinfo where (usercode=? or email=? or phone=?) and pwd=? ", new Object[]
						{ usercode, usercode, usercode, MD5.getMD5ofStr(pwd) });
				if (userlist == null || userlist.isEmpty() == true)
				{
					map.put("stat", "F");
					map.put("msg", "用户名或密码错误！");
				} else
				{
					UserInfo userinfo = userlist.get(0);
					//先判断是不是到期了
					boolean isEffectEnd=false;
					if(userinfo.getLongtimeeffect() !=null && userinfo.getLongtimeeffect()==0)
					{
						//不是长期有效，如果没有赋值到期日期，默认放过
						String endDateStr=userinfo.getEffecttime();
						if(endDateStr!=null && endDateStr.trim().equals("")==false)
						{
							SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
							Date endDate=sdf.parse(endDateStr);
							if(endDate.before(new Date()))
							{
								isEffectEnd=true;
								map.put("stat", "F");
								map.put("msg", "用户到期，请联系系统管理员！");
							}
						}
					}
					if(isEffectEnd==false)
					{
						UserInfoVo uservo = new UserInfoVo();
						BeanUtils.copyProperties(uservo, userinfo);
						session.setAttribute("user_session", uservo);
						map.put("stat", "S");
						map.put("msg", "");
						//直接跳转到首页
						//redirect("../index.jsp" );
					}
				}
			} else
			{
				map.put("stat", "F");
				map.put("msg", "验证码错误！");
			}
		} catch (Exception e)
		{
			log.error("登录异常！", e);
			map.put("stat", "F");
			map.put("msg", "登录异常！");
		}
		return new JsonView(map);
	}

	public View logout()
	{
		Map<String, Object> map = new HashMap<String, Object>();
		session.removeAttribute("user_session");
		map.put("stat", "S");
		return new JsonView(map);
	}

	public void loginform()
	{
	}

	public void list()
	{
		UserInfo UserInfo = new UserInfo();
		StringBuffer sql = new StringBuffer("select * from igs_UserInfo where 1=1 ");
		try
		{
			String pagenostr = request.getParameter("pageNo");
			String pagesizestr = request.getParameter("pageSize");
			if (pagenostr == null || "".equals(pagenostr.trim()))
			{
				pagenostr = "1";
			}
			if (pagesizestr == null || "".equals(pagesizestr.trim()))
			{
				pagesizestr = this.pagesize + "";
			}
			String fullname = request.getParameter("fullname");
			if(fullname!=null && fullname.trim().equals("")==false)
			{
				sql.append(" and fullname like '%"+fullname+"%' ");
			}
			String usercode = request.getParameter("usercode");
			if(usercode!=null && usercode.trim().equals("")==false)
			{
				sql.append(" and usercode like '%"+usercode+"%' ");
			}
			
			Page page = new Page(0, Integer.parseInt(pagenostr), Integer.parseInt(pagesizestr), null);
			List<Object> paramlist = new ArrayList<Object>();

			List<UserInfo> list = (List<UserInfo>) UserInfo.findBySql(UserInfo.getClass(), sql.toString(), paramlist.toArray(), "", page.getPageSize(), page.start);
			long count = UserInfo.count(UserInfo.getClass(), null, paramlist.toArray());
			page = new Page(count, Integer.parseInt(pagenostr), Integer.parseInt(pagesizestr), list);
			request.setAttribute("page", page);
		} catch (Exception e)
		{
			log.error("查看用户列表异常", e);
			request.setAttribute("msg_error", "访问出错");
		}
	}
	
	public TextView  gettodaynewmsgcount()
	{
		String resultStr="";
		try
		{
			Map<String, Object> map = new HashMap<String, Object>();
			String usercode=request.getParameter("usercode");
			String pwd=request.getParameter("pwd");
			UserInfo user = new UserInfo();
			List<UserInfo> userlist = (List<UserInfo>) user.findBySql(user.getClass(),
					"select * from igs_userinfo where (usercode=? or email=? or phone=?) and pwd=? ", new Object[]
					{ usercode, usercode, usercode, MD5.getMD5ofStr(pwd) });
			if (userlist == null || userlist.isEmpty() == true)
			{
				resultStr="Fail";
			} else
			{
				SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
				String strDate=df.format(new Date());
				UserInfo userinfo = userlist.get(0);
				int i=0;
				String querySql=" SELECT * FROM igs_downloadurl "
								+" where userid="+userinfo.getId()+" "
								//+" and SUBSTRING(recordtime,1,10)='"+strDate+"' "
								+" and isread=0 "
								;
				DownloadUrl msginfo=new DownloadUrl();
				List<DownloadUrl> list = (List<DownloadUrl>) msginfo.findBySql(DownloadUrl.class, querySql);
				if(list!=null && list.size()>0)
				{
					resultStr="yes";
				}
				else
				{
					resultStr="no";
				}
			}
			
		} catch (Exception e)
		{
			log.error("获取今天最新消息数量异常", e);
			resultStr="Fail";
		}
		return new TextView(resultStr);

	}
	
	public void gettodaynewmsg()
	{
		try
		{
			Map<String, Object> map = new HashMap<String, Object>();
			String usercode=request.getParameter("usercode");
			String pwd=request.getParameter("pwd");
			UserInfo user = new UserInfo();
			List<UserInfo> userlist = (List<UserInfo>) user.findBySql(user.getClass(),
					"select * from igs_userinfo where (usercode=? or email=? or phone=?) and pwd=? ", new Object[]
					{ usercode, usercode, usercode, MD5.getMD5ofStr(pwd) });
			if (userlist == null || userlist.isEmpty() == true)
			{
				request.setAttribute("stat", "F");
				request.setAttribute("msg", "用户名或密码错误！");
			} else
			{
				SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
				String strDate=df.format(new Date());
				UserInfo userinfo = userlist.get(0);
				int i=0;
				String querySql=" SELECT * FROM igs_downloadurl "
								+" where userid="+userinfo.getId()+" "
								//+" and SUBSTRING(recordtime,1,10)='"+strDate+"' "
								+" and isread=0 "
								;
				DownloadUrl msginfo=new DownloadUrl();
				List<DownloadUrl> list = (List<DownloadUrl>) msginfo.findBySql(DownloadUrl.class, querySql);
				if(list!=null && list.size()>0)
				{
					String updateSql=" update igs_downloadurl set isread=1 "
									+" where userid="+userinfo.getId()+" "
									//+" and SUBSTRING(recordtime,1,10)='"+strDate+"' "
									+" and isread=0 "
									;
					msginfo.execute(updateSql, null);
					request.setAttribute("dataLength", list.size());
					request.setAttribute("dataList", list);
				}
				else
				{
					request.setAttribute("dataLength", 0);
					request.setAttribute("dataList", null);
				}
				request.setAttribute("stat", "S");
			}
			
		} catch (Exception e)
		{
			log.error("获取今天最新消息异常", e);
			request.setAttribute("stat", "F");
			request.setAttribute("msg_error", "访问出错，请联系系统管理员！");
		}
	}
	
	/**
	 * 获取短信猫需要发送的数据
	 */
	public void gettodaydxmmsg()
	{
		try
		{
			Map<String, Object> map = new HashMap<String, Object>();
			String usercode=request.getParameter("usercode");
			String pwd=request.getParameter("pwd");
			UserInfo user = new UserInfo();
			List<UserInfo> userlist = (List<UserInfo>) user.findBySql(user.getClass(),
					"select * from igs_userinfo where (usercode=? or email=? or phone=?) and pwd=? ", new Object[]
					{ usercode, usercode, usercode, MD5.getMD5ofStr(pwd) });
			if (userlist == null || userlist.isEmpty() == true)
			{
				request.setAttribute("stat", "F");
				request.setAttribute("msg", "用户名或密码错误！");
			} else
			{
				if(QueryCountUtil.isTodayDownLoad)
					request.setAttribute("resultList",QueryCountUtil.getTodayUserMessageCount());
				request.setAttribute("stat", "S");
				request.setAttribute("msg", "用户登录成功！");
			}
			
		} catch (Exception e)
		{
			log.error("获取今天短信猫发送最新消息异常", e);
			request.setAttribute("stat", "F");
			request.setAttribute("msg", "用户名或密码错误！");
		}
	}
	
	/**
	 * 备份数据库
	 */
	public void backUpDB()
	{
		try
		{
			DBBackupUtil.backup();
			//直接跳转到首页
			redirect("/backup.jsp" );
		}
		catch(Exception ex)
		{
			log.error("备份数据库异常", ex);
		}
	}
	
	/**
	 * 备份数据库
	 */
	public void downloaddb()
	{
		try
		{
			String lastFilePath=DBBackupUtil.getLastDownLoadFile();
	        String dateStr=(new java.text.SimpleDateFormat("yyyyMMddhhmmss")).format(new Date());
			request.setAttribute("dateStr", dateStr);
			request.setAttribute("lastFilePath", lastFilePath);
		}
		catch(Exception ex)
		{
			log.error("下载数据库异常", ex);
		}
	}
	
}
